﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using PMS.BusinessFacade;
using PMS.EntityManage;
using PMS.Common;
using PMS.EntityQuery;
using System.Data.SqlClient;
using System.Collections.Generic;
using BusinessFacade;
using EntityManage;
using System.Text;

public partial class Modules_Personal_FirstAssignAdd : System.Web.UI.Page
{
    ISys_PostHandler postHandler = new Sys_PostManage();
    IPerf_Personal_TargetOwnerHandler toHandler = new Perf_Personal_TargetOwnerManage();
    IPerf_Personal_FirstAssignHandler firstAssignHandler = new Perf_Personal_FirstAssignManage();
    ISys_OrganizationHandlerExt orgExtHandler = new Sys_OrganizationManageExt();
    ISys_OrganizationHandler orgHandler = new Sys_OrganizationManage();

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!CheckPurviews())
        {
            Response.Redirect("~/Login.aspx");
        }
        if (!IsPostBack)
        {
            dataBind();
        }
    }

    private bool CheckPurviews()
    {
        if (Session["UserPurviews"] != null)
        {
            string strPur = Session["UserPurviews"].ToString();
            if (strPur.Contains("302011"))
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        else
        {
            return false;
        }
    }

    private void dataBind()
    {
        FillPost();
        FillTargetOwner();
        string tree = BuildOrgTree(0);
        treeContainer.InnerHtml = tree;
    }

    private void FillPost()
    {
        DataTable dt = postHandler.GetSys_PostList(" Status = @Status", new SqlParameter[]{new SqlParameter("@Status", (int)Enums.NormalStatus.Vallid)}, " id asc");
        ddlPost.DataTextField = "Name";
        ddlPost.DataValueField = "ID";
        ddlPost.DataSource = dt;
        ddlPost.DataBind();
    }

    private void FillTargetOwner()
    {
        DataTable dt = toHandler.GetPerf_Personal_TargetOwnerList();
        ddlTargetOwner.DataTextField = "Name";
        ddlTargetOwner.DataValueField = "ID";
        ddlTargetOwner.DataSource = dt;
        ddlTargetOwner.DataBind();
    }

    private string BuildOrgTree(int parentId)
    {
        StringBuilder builder = new StringBuilder();
        int parentId2 = parentId;
        if (parentId == 0)
        {
            Sys_OrganizationQuery root = orgExtHandler.GetRootOrganization();
            builder.Append("<li><input type=\"checkbox\" name=\"orgid\" value='" + root.ID + "' /><label>" + root.Name + "</label>");
            parentId2 = root.ID;
        }

        Sys_OrganizationQuery[] childList = orgHandler.GetSys_OrganizationQueryList(" Parent_ID = @Parent_ID and (Type = @Type1 or Type = @Type2)", 
            new SqlParameter[] { new SqlParameter("@Parent_ID", parentId2), new SqlParameter("@Type1", (int)Enums.OrgType.ICU), new SqlParameter("@Type2", (int)Enums.OrgType.Office) }, " ID asc");
        if (childList != null && childList.Length > 0)
        {
            builder.Append(parentId == 0 ? "<ul>" : "");
            foreach (Sys_OrganizationQuery query in childList)
            {
                builder.Append("<li><input type=\"checkbox\" name=\"orgid\" value='" + query.ID + "' /><label>" + query.Name + "</label>");
                string childStr = BuildOrgTree(query.ID);
                if (childStr != null && childStr != string.Empty && !"".Equals(childStr))
                    builder.Append("<ul>" + childStr + "</ul>");
                builder.Append("</li>");
            }
            builder.Append(parentId == 0 ? "</ul>" : "");
        }

        if (parentId == 0)
        {
            builder.Append("</li>");
        }

        return builder.ToString();
        
    }

    protected void btnSave_Click(object sender, EventArgs e)
    {
        if ("".Equals(hdnOrgID.Value.Trim()))
        {
            Jscript.Alert("请选择单位", this.Page);
            return;
        }
        if ("".Equals(ddlPost.SelectedValue.Trim()))
        {
            Jscript.Alert("请选择岗位", this.Page);
            return;
        }
        if ("".Equals(ddlTargetOwner.SelectedValue.Trim()))
        {
            Jscript.Alert("请选择指标套", this.Page);
        }

        List<Perf_Personal_FirstAssignQuery> list = new List<Perf_Personal_FirstAssignQuery>();
        // 根据单位ID，岗位ID，指标套ID，判断是否存在已分配的记录
        string[] orgIds = hdnOrgID.Value.Split(',');
        int postId = int.Parse(ddlPost.SelectedValue);
        int targetOwnerId = int.Parse(ddlTargetOwner.SelectedValue);
        foreach (string orgId in orgIds)
        {
            Sys_OrganizationQuery orgQuery = orgHandler.GetSys_OrganizationQuery(int.Parse(orgId));
            if (orgQuery != null)
            {
                if (orgQuery.Type != (int)Enums.OrgType.ICU && orgQuery.Type != (int)Enums.OrgType.Office)
                    continue;
            }

            string where = " Org_ID = @Org_ID and Post_ID = @Post_ID and TargetOwner_ID = @TargetOwner_ID";
            SqlParameter[] pams = new SqlParameter[] { new SqlParameter("@Org_ID", int.Parse(orgId)),
                new SqlParameter("@Post_ID", postId), new SqlParameter("@TargetOwner_ID", targetOwnerId)};
            DataTable dt = firstAssignHandler.GetPerf_Personal_FirstAssignByPageList(where, pams, 0, 2);
            if (dt != null && dt.Rows.Count > 0)
            {
                Jscript.Alert("在所选的单位及岗位中，存在已分配该指标套的单位。", this.Page);
                return;
            }
            else
            {
                Perf_Personal_FirstAssignQuery query = new Perf_Personal_FirstAssignQuery();
                query.User_ID = int.Parse(Session["CurrentUserID"].ToString());
                query.Org_ID = int.Parse(orgId);
                query.Post_ID = postId;
                query.TargetOwner_ID = targetOwnerId;
                query.Create_Time = DateTime.Now;
                query.Status = (int)Enums.PersonalFirstAssignStatus.NewAdded;

                list.Add(query);
            }
        }

        if (firstAssignHandler.InsertPerf_Personal_FirstAssign(list.ToArray()))
        {
            // 更新指标套的ID
            Perf_Personal_TargetOwnerQuery toQuery = toHandler.GetPerf_Personal_TargetOwnerQuery(targetOwnerId);
            if (toQuery != null)
            {
                if (toQuery.Status == (int)Enums.PersonalTargetOwnerStatus.NewAdded)
                {
                    toQuery.Status = (int)Enums.PersonalTargetOwnerStatus.Assigned;
                    toHandler.UpdatePerf_Personal_TargetOwner(toQuery);
                }
            }
            Jscript.Alert("分配成功！", this.Page);
            Jscript.ReturnAndClose(this.Page, "true");
        }
        else
        {
            Jscript.Alert("分配失败", this.Page);
        }
    }

}
